package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1、参数检测
        if(multipartFile==null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //2、检测用户是否登录
       WmUser wmUser= WmThreadLocalUtil.get();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2、将文件上传到minio中
        //2.1   生成唯一的文件名
        String originFilename=multipartFile.getOriginalFilename();   //1.jpg
        String suffix=  originFilename.substring(originFilename.lastIndexOf("."));  //suffix  ==    .jpg
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+suffix;

        //2.2   文件上传
        String filePath =null;
        try {
            filePath= fileStorageService.uploadImgFile("",fileName,multipartFile.getInputStream());
        } catch (IOException e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.UPLOAD_FAIL);
        }

        //3、将minio中的地址要记录wm_material表中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.get().getId());  //设置作者的id
        wmMaterial.setType((short)0);  //设置素材的类型为图片
        wmMaterial.setUrl(filePath);   //设置图片的访问 路径
        wmMaterial.setCreatedTime(new Date());  //设置图片上传的时间
        wmMaterial.setIsCollection((short)0);  //设置是否收藏（默认未收藏）
        this.save(wmMaterial);

        //4、返回wmMaterialc对象，前端做回显
        return ResponseResult.okResult(wmMaterial);
    }


    /**
     * 素材列表分页展示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1、参数检测
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        WmUser wmUser = WmThreadLocalUtil.get();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2、构造分页条件
        IPage page = new Page(dto.getPage(),dto.getSize());

        //3、构造查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //3.1 必须是当前登录用户的图片
        queryWrapper.eq(WmMaterial::getUserId,wmUser.getId());
        //3.2 判断是否收藏
        if(dto.getIsCollection()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //3.3 按照上传的时间进行降序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //4、带条件分页查询
        this.page(page,queryWrapper);

       //5、封装结果进行返回
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());


        return result;
    }
}
